package com.aaa.security;


import com.aaa.entity.ResponseMsg;
import com.aaa.entity.User;
import com.aaa.jwt.JwtTokenUtils;
import com.alibaba.fastjson.JSONObject;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Component
public class SuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        User principal = (User) authentication.getPrincipal();
        System.out.println(principal+"111111111111111");


        //响应设置
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setHeader("Content-Type","application/json");
        httpServletResponse.setStatus(200);
//

        String token = JwtTokenUtils.getToken(authentication);
        Map<String,Object> str =new HashMap<String,Object>();
        str.put("token",token);
        str.put("principal",principal);
        ResponseMsg msg = new ResponseMsg(200, "认证成功", str);
        //写：字节输出流
        PrintWriter writer = httpServletResponse.getWriter();
        writer.write(JSONObject.toJSONString(msg));
        writer.flush();
        writer.close();
    }


}
